<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/2/21 0021
 * Time: 下午 15:26
 */

namespace Org\Apply\InstallAndUninstall;


class InstallAndUnInstallApply extends Apply {


    /**
     * 安装应用方法
     * @param $applyName 应用名称
     * @return int|mixed
     */
    public function installApply($applyName)
    {
        $execute_sql = $this->install_sql($applyName); // 执行安装sql 语句
        $result = $this->install($applyName);
        if($result['status'] === 0) { //安装出错返回错误信息
            return $result;
        }

        // 程序安装没错了, 再执行 sql
        foreach($execute_sql as $sql) {
            $Model = new \Think\Model();
            $Model->execute($sql);
        }
        $this->addMenu($applyName);
        $result = $this->execute($applyName, 1); //安装成功后相应信息保存数据库
        return $result;

    }

    /**
     * 卸载安装应用
     * @param $applyName 应用名称
     * @return mixed|void
     */
    public function unInstallApply($applyName) {
//        $execute_sql = $this->uninstall_sql($applyName); // 执行卸载sql 语句
        $result = $this->uninstall($applyName);
        if($result['status'] === 0) { //卸载出错
            return $result;
        }

        // 程序卸载没错了, 再执行 sql
//        foreach($execute_sql as $sql) {
//            $Model = new \Think\Model();
//            $Model->execute($sql);
//        }

        $this->removeMenu($applyName);
        $result = $this->execute($applyName, 0);//卸载成功后相应信息保存数据库
        return $result;
    }

    /**
     * 判断文件是否修改
     */
    public function isEdit() {
        $controllerfile = $this->app_path . '/Application/Admin/Controller/AppDistributController.class.php';
        if (md5_file($controllerfile) != '' && md5_file($controllerfile) != '56f900f16fe6d86b41ed3c6b2bfa693b') {
            return false;
//            exit();
        } else {
            return true;
        }
    }

    /**
     * 公共执行方法
     * @param $applyName 应用名称
     * @param $status 安装或卸载 1为安装 0为卸载
     * @return mixed
     */
    private function execute($applyName, $status)
    {

        $model = M('Application');
        $condition['code'] = $applyName;
        $install['status'] = $status;
        $row = $model->where($condition)->save($install);
        if ($row) {
            //如果是物流应用 记录一条默认信息
            $info['status'] = 1;
            $info['msg'] = $install['status'] ? '安装成功!' : '卸载成功!';
        } else {
            $info['status'] = 0;
            $info['msg'] = $install['status'] ? '安装失败' : '卸载失败';
        }

        return $info;
    }
}